package exam.file.utils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @author Xiongx
 * @version 1.0
 * @date 2021/4/18 21:17
 * @since JDK 1.8
 *
 * 文件传输通用
 */
public class FileOutUtils {

    public static void fileOutByPath(String path,HttpServletResponse response){
        InputStream inputStream = null;
        OutputStream os = null;
        try{
            File file = new File(path);
            String name = file.getName();
            inputStream = new FileInputStream(file);
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len =0;
            while((len=inputStream.read(buffer))!=-1){
                outStream.write(buffer,0,len);
            }
            inputStream.close();
            byte[] data = outStream.toByteArray();
            response.reset();
            response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(name,"UTF-8"));
            response.setContentType("application/octet-stream");
            os = response.getOutputStream();
            os.write(data);
            os.flush();
            os.close();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if(inputStream!=null){
                    inputStream.close();
                }
                if(os!=null){
                    os.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
